package com.th.therp.service.Impl;

import com.th.therp.exception.BaseException;
import com.th.therp.mapper.MaterialBrandMapper;
import com.th.therp.pojo.emtity.MaterialBrand;
import com.th.therp.service.MaterialBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MaterialBrandServiceImpl implements MaterialBrandService {

    @Autowired
    private MaterialBrandMapper materialBrandMapper;

    @Override
    public List<MaterialBrand> list() {
        return materialBrandMapper.list();
    }

    @Override
    public void add(MaterialBrand materialBrand) {
        MaterialBrand existingMaterialBrand = materialBrandMapper.findByName(materialBrand.getName());
        if (existingMaterialBrand == null) {
            materialBrandMapper.add(materialBrand);
        }else {
            throw new BaseException("该品牌已存在");
        }
    }

    @Override
    public void update(MaterialBrand materialBrand) {
        MaterialBrand existingMaterialBrand = materialBrandMapper.findByName(materialBrand.getName());
        if (existingMaterialBrand != null && !existingMaterialBrand.getId().equals(materialBrand.getId())) {
            throw new BaseException("该品牌已存在");
        }else {
            materialBrandMapper.update(materialBrand);
        }
    }

    @Override
    public void delete(List<Integer> ids) {
        ids.forEach(id -> {
            MaterialBrand materialBrand = MaterialBrand.builder()
                    .id(id)
                    .isDeleted(1)
                    .build();
           materialBrandMapper.update(materialBrand);
        });
    }

    public String findBrandNameById(Integer brandId) {
        return materialBrandMapper.findBrandNameById(brandId);
    }
}
